package com.openxt.nbzj.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.internal.BottomNavigationMenuView;
import android.support.design.widget.BottomNavigationView;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.openxt.nbzj.R;
import com.openxt.nbzj.adapter.ViewPagerAdapter;
import com.openxt.nbzj.call.HeartBeatManager;
import com.openxt.nbzj.fragment.HomeFragment;
import com.openxt.nbzj.fragment.OpenxtBaseActivity;
import com.openxt.nbzj.fragment.OpenxtFragment;
import com.openxt.nbzj.fragment.OwnerFragment;
import com.openxt.nbzj.fragment.SpecialFragment;
import com.openxt.nbzj.fragment.SubscriptionFragment;
import com.openxt.nbzj.helper.BottomNavigationViewHelper;
import com.openxt.nbzj.model.ConfigModel;
import com.openxt.nbzj.model.RemotingModel;
import com.openxt.nbzj.plugins.AppPlugins;
import com.openxt.nbzj.remoting.ClientEx;
import com.openxt.nbzj.splashscreen.SplashScreenPage;
import com.openxt.nbzj.update.AutoUpdateEx;
import com.openxt.nbzj.util.DensityUtil;
import com.openxt.nbzj.util.StringUtil;
import com.openxt.nbzj.view.ProhibitScrollViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import qs.openxt.libs.util.ActivityUtil;
import qs.openxt.libs.util.Utils;

/**
 * Created by 颖杰_2 on 2016/7/5.
 */
public class HomeActivity extends OpenxtBaseActivity implements BottomNavigationView.OnNavigationItemSelectedListener {

    @BindView(R.id.viewpager)
    ProhibitScrollViewPager viewPager;
    @BindView(R.id.bottom_navigation)
    BottomNavigationView bottomNavigation;

    private ViewPagerAdapter adapter;
    private OpenxtFragment currentFragment = null;
    private List<OpenxtFragment> mList = new ArrayList<>();
    private Handler mHandler = new Handler();
    private SplashScreenPage splashScreenPage = null;
    private Context mContext = null;
    private final static int LOGIN = 0x406;
    private int goToPosition = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        showCustomSplashScreen();

        super.onCreate(savedInstanceState);

        setContentView(R.layout.home);
        ButterKnife.bind(this);
        setActionUrl("#/");
        mContext = this;

        String val = Utils.getLocalStorage(mContext, ConfigModel.LOGIN_NATIVE);
        if (!StringUtil.isNull(val)) {
            JSONObject data = JSON.parseObject(val);
            ClientEx.CUSTOMERID = StringUtil.doubleToLString(data.getString("USERID"));
            Utils.setLocalStorage(this, ClientEx.CUSTOMERID_KEY, ClientEx.CUSTOMERID);
        }

        setupViewPager();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (splashScreenPage != null) {
                    splashScreenPage.close();
                    splashScreenPage = null;
                }

                AppPlugins.init(mContext);
                //调用更新
                JSONObject param = new JSONObject();
                param.put("type", "android");
                param.put("Version", ActivityUtil.getVersion(mContext));
                AutoUpdateEx autoUpdateEx = new AutoUpdateEx(mContext, RemotingModel.SERVERURL + RemotingModel.CHECKVERSION, param, false);
                autoUpdateEx.update();

                if (RemotingModel.isLogin()) {
                    String val = Utils.getLocalStorage(mContext, ConfigModel.LOGIN_NATIVE);
                    if (!StringUtil.isNull(val)) {
                        JSONObject json = JSON.parseObject(val);
                        HeartBeatManager.instance().start(mContext, json.getInteger("HeartBeatMinutes"));
                    }
                }
            }
        }, 1000);
    }

    private void showCustomSplashScreen() {
        splashScreenPage = new SplashScreenPage(this, R.mipmap.page);
        splashScreenPage.loadPage();
    }

    public void setCurrentItem(int position) {
        bottomNavigation.getMenu().getItem(position).setChecked(true);
        viewPager.setCurrentItem(position, false);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                currentFragment.willBeDisplayed();
                currentFragment = adapter.getCurrentFragment();
                currentFragment.refresh();
            }
        }, 0);
    }

    public void setupViewPager() {
        BottomNavigationViewHelper.disableShiftMode(bottomNavigation);
        bottomNavigation.setOnNavigationItemSelectedListener(this);

        //设置icon的大小
        BottomNavigationMenuView menuView = (BottomNavigationMenuView) bottomNavigation.getChildAt(0);
        for (int i = 0; i < menuView.getChildCount(); i++) {
            final View iconView = menuView.getChildAt(i).findViewById(android.support.design.R.id.icon);
            final ViewGroup.LayoutParams layoutParams = iconView.getLayoutParams();
            layoutParams.height = DensityUtil.dip2px(mContext, 18);
            layoutParams.width = DensityUtil.dip2px(mContext, 18);
            iconView.setLayoutParams(layoutParams);
        }

        OpenxtFragment fragment = new HomeFragment();
        fragment.setName(getString(R.string.tab1));
        mList.add(fragment);

        fragment = new SubscriptionFragment();
        fragment.setName(getString(R.string.tab2));
        mList.add(fragment);

        fragment = new SpecialFragment();
        fragment.setName(getString(R.string.tab3));
        mList.add(fragment);

        fragment = new OwnerFragment();
        fragment.setName(getString(R.string.tab4));
        mList.add(fragment);

        adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.setList(mList);
        viewPager.setOffscreenPageLimit(4);
        viewPager.setAdapter(adapter);

        currentFragment = mList.get(0);
    }

    @Override
    protected void onDestroy() {
        HeartBeatManager.instance().stop();
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                currentFragment.refresh();
            }
        }, 10);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == LOGIN) {
            setCurrentItem(goToPosition);
        }
        if (currentFragment != null)
            currentFragment.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int position = 0;
        switch (item.getItemId()) {
            case R.id.tab1:
                position = 0;
                break;
            case R.id.tab2:
                position = 1;
                break;
            case R.id.tab3:
                position = 2;
                break;
            case R.id.tab4:
                position = 3;
                break;
        }
        currentFragment = adapter.getCurrentFragment();
        if ((position == 1 || position == 3) && !RemotingModel.isLogin()) {
            showMsg("请先登录");
            goToPosition = position;
            toActivityForResult(LoginActivity.class, null, LOGIN);
            return false;
        }
        setCurrentItem(position);
        return true;
    }
}